Looping in Python

Now that we know about basic collection types in Python, let's see how to iterate over them

Python range function

Before we take a look at the loops, it is a good time to learn about the python built in function: range

range() as its name implies, returns a list of numbers in the given range. Let's see a few examples:


In [13]:
print range(10)


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

By default range starts at the value 0 (as seen above) and goes till one value before the value specified to it. We can give it an explicit starting value as well


In [14]:
print range(2, 10)


[2, 3, 4, 5, 6, 7, 8, 9]

One more possible variation is to specify the step size between successive values


In [17]:
print range(0, 101, 10) #Step size of 10


[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

For loop

Let's see how to print each element of a list


In [12]:
for i in range(10):
    print i


0
1
2
3
4
5
6
7
8
9

If we wanted to print the square of each number in the list?


In [18]:
list1 = range(10)
for i in list1:
    print i ** 2


0
1
4
9
16
25
36
49
64
81

For loop over a string

You can loop through the characters of a String too


In [4]:
name = 'Alice'
for c in name:
    print c


A
l
i
c
e

Looping over a tuple

Looping through a tuple is similar


In [5]:
tup = (1, 2, 3, 4)
for i in tup:
    print i


1
2
3
4

Looping over a dictionary

Unlike lists, dictionaries contain key, value pairs instead of a single object. Looping through dicts is a bit different as we will see

Printing all the keys of a dictionary


In [6]:
d = {}
d['foo'] = 1
d['bar'] = 2
d['baz'] = 3

for k in d:
    print k


baz
foo
bar

Notice the keys are not printed in the same order in which they were added to the dict. Dictionaries do not maintain order

Printing the values of the dictionary


In [8]:
for v in d.values():
    print v


3
1
2

Printing both key and values in a dictionary


In [10]:
for k, v in d.items():
    print k, v


baz 3
foo 1
bar 2

While loops in Python

While loops in Python are similar to other languages


In [11]:
i = 10
while i > 0:
    print i
    i = i -1


10
9
8
7
6
5
4
3
2
1

Exercise:

  • How would you loop through a list and print the value of the item along with its index?
  • How would you loop through a list in the reverse order?

In [ ]: